﻿using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using HashFoo.MigratorFoo;

namespace HashFoo.MigratorFooTests
{
    class Helpers
    {
        public static string MockAssemblyPath
        {
            get
            {
                return Path.Combine(
                    Assembly.GetExecutingAssembly().GetCodeBaseDir(), 
                    "mockassembly_bin\\MigratorFoo.MockAssembly.dll");
            }
        }

        public static MigrationConfiguration MigrationConfiguration
        {
            get
            {
                return new MigrationConfiguration
                {
                    DbConfigAssemblyPath = MockAssemblyPath,
                    DownScriptsDirectory = Path.Combine(Assembly.GetExecutingAssembly().GetCodeBaseDir(), "Migrations\\Down"),
                    UpScriptsDirectory = Path.Combine(Assembly.GetExecutingAssembly().GetCodeBaseDir(), "Migrations\\Up"),
                    SchemaVersionTableName = "SchemaVersion"
                };
            }
        }

        public static MigrationManagerWorker CreateDefaultMigrationManagerWorker()
        {
            return new MigrationManagerWorker(MigrationConfiguration);
        }

        public static void NukeDatabase()
        {
            // we assume we're using sql
            //  we could also set "Pooling=false" in the connection string in the mock assembly
            //  however, that may mess with any sort of load tests we'd want to do in the future.
            SqlConnection.ClearAllPools();

            const string connectionString = @"Data Source=(local);Initial Catalog=master;Integrated Security=True;Pooling=False";
            using (var dbConn = new SqlConnection(connectionString))
            {
                try
                {
                    dbConn.Open();

                    using (var command = dbConn.CreateCommand())
                    {
                        command.CommandText =
                                @"  if DB_ID('MigratorFoo.Test') is not null
                                    ALTER DATABASE [MigratorFoo.Test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

                                    if DB_ID('MigratorFoo.Test') is not null
	                                drop database [MigratorFoo.Test];
                            
                                    if DB_ID('MigratorFoo.Test') is null
	                                    create database [MigratorFoo.Test];";

                        command.ExecuteNonQuery();
                    }
                }
                finally
                {
                    dbConn.Close();
                }
            }
        }
    }
}
